//
//  ZYJSONResponseSerializer.m
//  ZYWebImage
//
//  Created by wzp on 2025/4/8.
//

#import "ZYJSONResponseSerializer.h"

@implementation ZYJSONResponseSerializer

static id ZYJSONObjectByRemovingKeysWithNullValues(id jsonObj)
{
    if ([jsonObj isKindOfClass:[NSArray class]]) {
        NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:((NSArray *)jsonObj).count];
        for (id obj in ((NSArray *)jsonObj)) {
            if (obj && ![obj isKindOfClass:NSNull.class] && ![obj isEqual:[NSNull null]]) {
                [mutableArray addObject:ZYJSONObjectByRemovingKeysWithNullValues(obj)];
            }
        }
        return mutableArray;
    }
    else if ([jsonObj isKindOfClass:[NSDictionary class]]) {
        NSMutableDictionary *mutableDict = [NSMutableDictionary dictionaryWithDictionary:jsonObj];
        for (id key in [(NSDictionary *)jsonObj allKeys]) {
            id value = [(NSDictionary *)jsonObj objectForKey:key];
            if (!value || [value isKindOfClass:NSNull.class] || [value isEqual:[NSNull null]]) {
                [mutableDict removeObjectForKey:key];
            }
            else if ([value isKindOfClass:NSArray.class] || [value isKindOfClass:NSDictionary.class]) {
                mutableDict[key] = ZYJSONObjectByRemovingKeysWithNullValues(value);
            }
        }
        return mutableDict;
    }
    return jsonObj;
}

+ (instancetype)serializer
{
    return [[self alloc] initWithOptions:0];
}

+ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions {
    ZYJSONResponseSerializer *serializer = [[self alloc] initWithOptions:readingOptions];
    return serializer;
}

- (instancetype)initWithOptions:(NSJSONReadingOptions)readingOptions
{
    if (self = [super init]) {
        self.readingOptions = readingOptions;
        self.removesKeysWithNullValues = NO;
        self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
    }
    return self;
}

- (id)responseObjectForResponse:(NSURLResponse *)response data:(NSData *)data error:(NSError * _Nullable __autoreleasing *)error
{
    if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
        return nil;
    }
    
    BOOL isSpace = [data isEqualToData:[NSData dataWithBytes:" " length:1]];
    
    if (data.length == 0 || isSpace) {
        return nil;
    }
    
    NSError *serializationError = nil;
    
    id responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError];
    
    if (!responseObject)
    {
        if (error) {
            *error = serializationError;
        }
        return nil;
    }
    
    if (self.removesKeysWithNullValues) {
        return ZYJSONObjectByRemovingKeysWithNullValues(responseObject);
    }
    return responseObject;
    
}
@end
